﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Carbon.Web.Forms;

namespace Demo
{
    public class ImageHandler : IHttpHandler
    {
        public bool IsReusable
        {
            get { return false; }
        }


        public static String GetFileReferenceImageUrl(FileReference reference)
        {
            if (reference == null)
                return "/css/a/PageNotFound.jpg";
            return GetFileReferenceImageUrl(reference, null, null);
        }

        public static String GetFileReferenceImageUrl(FileReference reference, int? width, int? height)
        {
            String serializedId = InternalUtility.CompactSerialize(reference.Id);
            return "/images?id=" + InternalUtility.UrlEncode(serializedId) + "&key=" + reference.Key + (width != null ? "&width=" + width : string.Empty) + (height != null ? "&height=" + height : string.Empty);
        }

        public void ProcessRequest(HttpContext context)
        {
            Log.ExecuteWithLog(() =>
                {

                    int? width = null;
                    int? height = null;

                    String sWidth = context.Request.QueryString["width"];
                    String sHeight = context.Request.QueryString["height"];

                    if (!string.IsNullOrEmpty(sWidth))
                        width = ConvertInvariant.ToInt32(sWidth);

                    if (!string.IsNullOrEmpty(sHeight))
                        height = ConvertInvariant.ToInt32(sHeight);

                    if (((width == null && height == null) || (width != null && height != null)) == false) throw new InvalidOperationException("((width == null && height == null) || (width != null && height != null)) == false");

                    byte[] result = null;
                    ImageType imageType;

                    {
                        if (string.IsNullOrEmpty(context.Request.QueryString["id"])) throw new ArgumentOutOfRangeException("context.Request.QueryString[\"id\"]");
                        if (string.IsNullOrEmpty(context.Request.QueryString["key"])) throw new ArgumentOutOfRangeException("context.Request.QueryString[\"key\"]");

                        String id = ConvertInvariant.ToString(context.Request.QueryString["id"]);
                        Guid key = new Guid(context.Request.QueryString["key"]);

                        FileReference fileReference = new FileReference(id, key, string.Empty);

                        byte[] content = FormsContext.Current.PersistanceService.LoadFile(fileReference);

                        if (string.IsNullOrEmpty(fileReference.Name)) throw new ArgumentOutOfRangeException("fileReference.Name");

                        imageType = ImageUtility.GetImageTypeFromExtension(DemoUtility.GetExtensionFromFilename(fileReference.Name));
                        result = content;
                    }

                    context.Response.ContentType = ImageUtility.GetContentTypeFromImageType(imageType);
                    context.Response.Cache.SetCacheability(HttpCacheability.Public);
                    context.Response.Cache.SetExpires(DateTime.Now.AddYears(1));

                    if (width == null)
                    {
                        context.Response.OutputStream.Write(result, 0, result.Length);
                    }
                    else
                    {
                        ImageUtility.ResizeImage(imageType, result, width.Value, height.Value, context.Response.OutputStream);
                    }
                    context.Response.End();
                });
        }
    }
}